package com.will.netty.channel;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * @author Will
 * @description:
 *              客户端代码
 *              connect() 为异步方法，要想在连接建立后加上一些处理，
 *              就需要调用 sync() 同步阻塞，
 *              或者使用异步回调的方式，由 nio 线程在建立连接后调用 ChannelFutureListener 中的 operationComplete 方法
 * @date 2023-05-17 22:45
 * @version: 1.0
 */
@Slf4j
public class ChannelFutureClient {
    public static void main(String[] args) throws InterruptedException {
        ChannelFuture channelFuture = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(
                        new ChannelInitializer<NioSocketChannel>() {
                            @Override // 在连接建立后被调用
                            protected void initChannel(NioSocketChannel ch) throws Exception {
                                log.debug("init...");
                                ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                                ch.pipeline().addLast(new StringEncoder());
                            }
                        })
                .connect(new InetSocketAddress("localhost", 8080));

        // sync() 同步阻塞
//        log.debug("{}", channelFuture.channel());
//        channelFuture.sync();
//        log.debug("{}", channelFuture.channel());

        // 异步回调
        log.debug("{}", channelFuture.channel());
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                log.debug("{}", channelFuture.channel());
            }
        });
    }
}
